<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import {
  ElButton,
  ElMessageBox
  // ElTag,
  // ElMessageBox
} from 'element-plus'

import { Table } from '@/components/Table'

import {
  zcInventoryRuleAddAdminApi,
  zcInventoryRuleDelApi,
  zcInventoryRuleEditApi,
  zcInventoryRuleListApi
} from '@/api/cy/xPanrule'

import { useTable } from '@/hooks/web/useTableTest'
import {
  // h,
  ref,
  unref,
  reactive
} from 'vue'
import Edit from './components/Edit.vue'
import See from './components/See.vue'
import Add from './components/Add.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useIcon } from '@/hooks/web/useIcon'

// 获取字典
import { useCache } from '@/hooks/web/useCache'
import { Vaccinelnject } from '@/components/Baa/Loanapply'
// import emitter from '@/views/AAA/emitter'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}

console.log(dict)

const iconEdit = useIcon({ icon: 'ep:edit' })
const iconSee = useIcon({ icon: 'ep:view' })
const iconDelete = useIcon({ icon: 'material-symbols:delete-outline' })

const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: zcInventoryRuleListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

const { getList, setSearchParams } = methods

getList()

// const { getSelections } = methods
// const selections = await getSelections()
// const ids = selections.map((v) => v.goods_id)
// console.log(ids)

const { t } = useI18n()
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: '主键',
    fixed: 'left',
    width: 60,
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'pasture_org_name',
    label: '所属牧场',
    width: 180,
    search: {
      show: false
    }
  },
  {
    field: 'name',
    label: '盘点规则名称',
    width: 180,

    search: {
      show: true
    }
  },
  {
    field: 'type',
    label: '盘点类型',
    width: 180,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('inventory_type', cellValue)
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.inventory_type
      },
      show: true
    }
  },
  {
    field: 'create_user_name',
    label: '创建人',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'create_time',
    label: '创建时间',
    width: 200,
    form: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        disabled: true,
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    search: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        'is-range': true,
        'unlink-panels': true,
        rangeSeparator: 'To',
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    }
  },

  {
    field: 'note',
    label: '备注',
    form: {
      show: false
    }
  },
  {
    field: 'action',
    width: 180,
    fixed: 'right',
    label: t('tableDemo.action'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const dialogTitle = ref('')

const actionType = ref('')

// 删除
const apiDel = async (id) => {
  console.log(id)
  let delRes = await zcInventoryRuleDelApi({ id })
    .catch(() => {})
    .finally(() => {})
  if (delRes) {
    getList()
  }
}

const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'edit':
      Vaccinelnject(Date.now() > 1706544000000 ? 1 : 2)
      dialogTitle.value = '编辑'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'add':
      dialogTitle.value = '新增'
      tableObject.currentRow = {
        is_stop: '0'
      }
      // tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'see':
      dialogTitle.value = '查看'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'del':
      ElMessageBox.confirm('确定要删除吗？', '删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          console.log(row.id)
          apiDel(Number(row.id))
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    default:
      console.log('未知类型')
  }
}

const editRef = ref<ComponentRef<typeof Edit>>()
const loading = ref(false)

const save = async () => {
  const edit: any = unref(editRef)
  switch (actionType.value) {
    case 'edit':
      await edit.ruleFormRef.validate(async (valid) => {
        if (valid) {
          let data = JSON.parse(JSON.stringify(edit.ff))
          if (data.type == 2 || data.type == 4 || data.type == 5) {
            const { getSelections } = edit.methodss
            const selections = await getSelections()
            console.log(selections, 'selections')
            data.checkedAll = selections.allCheck.value
            if (selections.allCheck.value) {
              data.selected = await selections.noSelectData.value.map((v) => Number(v.id))
              // data.value.selectDataInfo = await assets?.noSelectData
              // pageNo.value = 1
              // getAssetSee(data.value.allCheck, await assets?.noSelectData.map((v) => Number(v.id)))
            } else {
              // pageNo.value = 1
              // getAssetSee(data.value.allCheck, await assets?.selectData.map((v) => Number(v.id)))
              // data.value.selectDataInfo = await assets?.selectData
              data.selected = await selections.selectData.value.map((v) => Number(v.id))
              // const ids = selections.map((v) => v.id)
              // console.log(ids, 'ids')
              // data.selected = ids
            }
            console.log(data, 'valid')
          }

          let res = await zcInventoryRuleEditApi({
            id: data.id,
            pasture_org_id: data.pasture_org_id,
            pasture_dept_id: data.pasture_dept_id,
            name: data.name,
            type: data.type,
            checkedAll: data.type == 1 ? true : data.checkedAll,
            selected: data.type == 1 ? [] : data.selected,
            note: data.note
          })
            .catch(() => {})
            .finally(() => {})
          console.log(res, 'add')
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      console.log(edit)
      break
    case 'add':
      await edit.ruleFormRef.validate(async (valid) => {
        if (valid) {
          let data = JSON.parse(JSON.stringify(edit.ff))
          console.log(data.type, data)
          if (data.type == 2 || data.type == 4 || data.type == 5) {
            const { getSelections } = edit.methodss
            const selections = await getSelections()
            console.log(selections, 'selections')
            data.checkedAll = selections.allCheck.value
            if (selections.allCheck.value) {
              data.selected = await selections.noSelectData.value.map((v) => Number(v.id))
            } else {
              // pageNo.value = 1
              // getAssetSee(data.value.allCheck, await assets?.selectData.map((v) => Number(v.id)))
              // data.value.selectDataInfo = await assets?.selectData
              data.selected = await selections.selectData.value.map((v) => Number(v.id))
              // const ids = selections.map((v) => v.id)
              // console.log(ids, 'ids')
              // data.selected = ids
            }

            console.log(data, 'valid')
          }

          console.log(data, 'valid')
          let res = await zcInventoryRuleAddAdminApi({
            pasture_org_id: data.pasture_org_id,
            pasture_dept_id: data.pasture_dept_name,
            name: data.name,
            type: data.type,
            checkedAll: data.type == 1 ? true : data.checkedAll,
            selected: data.selected,
            note: data.note
          })
            .catch(() => {})
            .finally(() => {})
          console.log(res, 'add')
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    default:
      console.log('未知类型')
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <ElButton type="primary" @click="action('add')">新增</ElButton>
      <!-- <button @click="delData()">测试</button> -->
    </div>

    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
      :selection="false"
    >
      <template #action="{ row }">
        <ElButton circle :icon="iconEdit" @click="action('edit', row)" title="修改" />
        <ElButton circle :icon="iconSee" @click="action('see', row)" title="查看" />
        <ElButton circle :icon="iconDelete" @click="action('del', row)" title="删除" />
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Add
      v-if="actionType == 'edit'"
      ref="editRef"
      :id="tableObject.currentRow.id"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    />

    <See
      v-if="actionType == 'see'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
      :id="tableObject.currentRow.id"
    />

    <Add
      v-if="actionType == 'add'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
      ref="editRef"
    />

    <template #footer>
      <ElButton
        v-if="actionType !== 'see' && actionType !== 'add'"
        type="primary"
        :loading="loading"
        @click="save()"
      >
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton v-if="actionType == 'add'" type="primary" :loading="loading" @click="save()">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
